#!/bin/sh
# frozen_string_literal: true

# Copyright the Linux Foundation and the CII Best Practices badge contributors
# SPDX-License-Identifier: MIT

# Validate branch name for CI/CD pipelines
# Implements OSPS-BR-01.02: Branch name sanitization and validation
#
# This script validates that branch names contain only safe characters
# and don't start with characters that could be confused as option flags.
# This prevents command injection and cache poisoning attacks.
#
# Usage: validate_branch_name BRANCH_NAME
#
# Exit codes:
#   0 - Branch name is valid
#   1 - Branch name is invalid

set -e

# Check for required argument
if [ $# -ne 1 ]; then
  echo "Usage: $0 BRANCH_NAME" >&2
  exit 1
fi

BRANCH_NAME="$1"

# Reject empty branch name
if [ $# = '' ]; then
  echo "ERROR: Branch name must not be empty" >&2
  exit 1
fi

# Reject branch names starting with hyphen
# (these could be confused as being an option flag)
case "$BRANCH_NAME" in
  -*)
    echo "ERROR: Branch name must not start with '-': $BRANCH_NAME" >&2
    exit 1
    ;;
esac

# Reject branch names starting with /
# (these could be confused as being an absolute path)
case "$BRANCH_NAME" in
  /*)
    echo "ERROR: Branch name must not start with '/': $BRANCH_NAME" >&2
    exit 1
    ;;
esac

# Reject branch names including ..
# (these could escape up a directory)
case "$BRANCH_NAME" in
  *..*)
    echo "ERROR: Branch name must not include ..: $BRANCH_NAME" >&2
    exit 1
    ;;
esac

# Validate allowed characters using POSIX-compliant case statement
# Allowed: A-Z, a-z, 0-9, /, _, ., +, -
case "$BRANCH_NAME" in
  *[!A-Za-z0-9/_.+-]*)
    echo "ERROR: Branch name has unsafe characters: $BRANCH_NAME" >&2
    echo "Branch names only allow A-Za-z0-9/_.+-" >&2
    exit 1
    ;;
esac

# Length check (POSIX-compliant)
BRANCH_LENGTH=$(printf '%s' "$BRANCH_NAME" | wc -c)
if [ "$BRANCH_LENGTH" -gt 200 ]; then
  echo "ERROR: Branch name too long: $BRANCH_LENGTH characters" >&2
  exit 1
fi

echo "Branch name validated (per OSPS-BR-01.02): $BRANCH_NAME"
exit 0
